/**
 * @author ming
 * @date 2021/2/15 19:39
 * @desc ip 工具类
 */
package common

import "net"

func LocalIPs() ([]net.IP, error) {
	result := make([]net.IP, 0, 4)
	interfaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for _, item := range interfaces {
		if item.Flags&net.FlagUp == 0 {
			continue // interface down
		}
		if item.Flags&net.FlagLoopback != 0 {
			continue // loopback interface
		}

		addresses, err := item.Addrs()
		if err != nil {
			return nil, err
		}
		for _, addr := range addresses {
			ip := getIpFromAddr(addr)
			if ip == nil {
				continue
			}
			result = append(result, ip)
		}
	}
	return result, nil
}

func getIpFromAddr(addr net.Addr) net.IP {
	var ip net.IP
	switch v := addr.(type) {
	case *net.IPNet:
		ip = v.IP
	case *net.IPAddr:
		ip = v.IP
	}
	if ip == nil || ip.IsLoopback() {
		return nil
	}
	ip = ip.To4()
	if ip == nil {
		return nil // not an ipv4 address
	}

	return ip
}
